<script setup lang="ts">
import useToast from '@/hooks/useToast';
import HomeRequest from '@/request/homeRequest';
import { useAppStore } from '@/store';
import to from '@/utils/to';
import Tools from '@/utils/tools';

interface IProps {
  data: IGoodsAdditionalInfo;
}

type EmitEvents = {
  (event: 'change', payload: { value: string }): void;
};

const props = defineProps<IProps>();
const emits = defineEmits<EmitEvents>();
const show = ref<boolean>(false);
const _value = ref<string>(props.data.value || '');
const fieldOptions = ref<string>(props.data.fieldOptions);
const { showToast } = useToast();

onMounted(async () => {
  if (props.data.fieldName === 'timerinterval' && props.data.dockData === 'cxry') {
    const { timeStamp, doctorId } = useAppStore().$state.registerData;
    const [err, res] = await to(HomeRequest.ObtainListDoctorTime({ hasLoading: true, date: Tools.formatTimestamp(timeStamp, 'YYYY-MM-DD'), doctorId }));
    if (err) {
      showToast('暂无可预约的时间');
      return;
    }
    fieldOptions.value = JSON.stringify(
      res.data.map((item) => {
        return { name: `${item.begintime}-${item.endtime}`, id: `${item.begintime}-${item.endtime}` };
      }),
    );
  }
});

const communityList = computed(() => {
  return JSON.parse(fieldOptions.value).map((_item: any) => {
    return { text: _item.name, value: _item.id };
  });
});

const handlePickerChange = (value: string, type: 'change' | 'confirm') => {
  emits('change', { value });
  _value.value = value;
  if (type === 'confirm') show.value = false;
};
</script>

<template>
  <van-cell :title="props.data.attrName" :required="props.data.requiredFlag" is-link @click="show = !show">
    <view class="c-text-color-grey text-align-left c-text-12" v-if="!_value">请选择{{ props.data.attrName }}</view>
    <view class="text-align-left c-text-12 c-color-black" v-else>{{ communityList.find((item: any) => item.value === _value).text }}</view>
  </van-cell>
  <van-popup position="bottom" round :show="show" @close="show = false">
    <view class="bg-white w-full">
      <van-picker show-toolbar :columns="communityList" :title="`请选择${props.data.attrName}`" @cancel="show = false" @confirm="(e: any) => handlePickerChange(e.detail.value.value, 'confirm')" @change="(e: any) => handlePickerChange(e.detail.value.value, 'change')" />
    </view>
  </van-popup>
</template>
